from flask import g
import jwt
import functools
import datetime


# 构造header
headers = {
    'typ': 'jwt',
    'alg': 'HS256'
}

# 密钥
SALT = 'HututuSys'


def create_token(userrole, password):
    # 构造payload
    payload = {
        'userrole': userrole,
        'password': password,  # 自定义用户ID
        'exp': datetime.datetime.utcnow() + datetime.timedelta(days=7)  # 超时时间
    }
    result = jwt.encode(payload=payload, key=SALT, algorithm="HS256", headers=headers)
    return result



def login_required(f):
    '让装饰器装饰的函数属性不会变 -- name属性'
    '第1种方法,使用functools模块的wraps装饰内部函数'
    @functools.wraps(f)
    def wrapper(*args, **kwargs):
        try:
            if g.username == 'timeoutToken':
                return {'code': 4001, 'message': 'token已失效'}, 401
            elif g.username == 'failToken':
                return {'code': 4001, 'message': 'token认证失败'}, 401
            elif g.username == 'illegalToken':
                return {'code': 4001, 'message': '非法的token'}, 401
            else:
                return f(*args, **kwargs)
        except BaseException as e:
            return {'code': 4001, 'message': '请先登录认证.'}, 401

    return wrapper



